package com.aita.diamond.service

import com.gd.magic.Service
import com.aita.diamond.Diamond
import com.aita.diamond.PurchaseBill
import com.aita.diamond.Order
import com.gd.domain.party.Operator
import com.gd.domain.constant.LogConstant
import java.text.SimpleDateFormat
import org.hibernate.Query

class PurchaseBillService implements Service {
			
	public static final String FORMAT_YEARMONTH = "yyyyMM"
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")	
	
	def addBill(def data,String diamonds){
		def purchaseBill=null
		if(data.id){
			purchaseBill=PurchaseBill.load(data.id)
			List pBillOfDiamonds = Diamond.findByPurchaseBill(purchaseBill)
		}else{
			purchaseBill=new PurchaseBill()
			purchaseBill.purchaseTime =  new Date();
			purchaseBill.org = loginService.currentOrg()
			purchaseBill.oper = loginService.currentOperator()
			assert data.uniqueCode : X("新增采购单，必须提供采购单编号")
			assert !PurchaseBill.loadByUniqueCode(data.uniqueCode) : X("采购单已存在，请检查采购单编号")
			purchaseBill.uniqueCode = data.uniqueCode
		}
		println "diamonds data = "+diamonds
		purchaseBill.amount = Long.parseLong(data.amount);
		
		purchaseBill.uniqueCode = data.uniqueCode
		purchaseBill.purchaseBillStatus = 1
		purchaseBill.purchaseTime = new Date()
		purchaseBill.type = Integer.parseInt(data.type)
		purchaseBill.diamondType = Integer.parseInt(data.diamondType)
		//data.completeDate
		if(data.completeDate){
			purchaseBill.completeDate = sdf.parse(data.completeDate)
		}
		if(data.order){
			println "data.order="+data.order
			Order order = Order.load(data.order)
			purchaseBill.order = order
			purchaseBill.persistOrMerge();
			logService.log(102015,"新建订单采购单"+purchaseBill.id)
			List orderOfDiamonds = Diamond.findByOrder(order)
			println "orderOfDiamonds.size()="+orderOfDiamonds.size()
			orderOfDiamonds.each(){
				it.purchaseBill=purchaseBill  //关联采购单
				if(data.discount){
					it.discount = Long.parseLong(data.discount);
					it.costPrice = Long.parseLong(data.costPrice);
					it.certificateType = Integer.parseInt(data.certificateType)
//					it.certificateNo = data.certificateNo
				}
				it.type = 2   //订单采购
				println "it.diamondStatus="+it.diamondStatus
				it.persistOrMerge()
			}
			order.orderStatus=3				//3,定制中
			order.persistOrMerge()
		}
		purchaseBill.provider = data.provider
		purchaseBill.comments = data.comments
		purchaseBill.persistOrMerge();
		logService.log(102010,"新建自主采购单"+purchaseBill.id)
		if(diamonds){
			List diamondList= diamonds.split(",")
			diamondList.each(){
				def diamond=Diamond.load(Long.parseLong(it))
				assert diamond : X("钻石不存在")
				assert !diamond.purchaseBill || diamond.purchaseBill == purchaseBill: X("钻石已经关联了采购单")
				diamond.purchaseBill=purchaseBill
				diamond.persistOrMerge()
			}
		}
	}
	def editBill(def data){
		
		println data.completeDate
		def purchaseBill=PurchaseBill.load(data.id)
		purchaseBill.amount = Long.parseLong(data.amount);
		//data.completeDate
		if(data.completeDate){
			purchaseBill.completeDate = sdf.parse(data.completeDate)
		}
		if(data.order){
			println "data.order"+data.order
			purchaseBill.order=Order.load(data.order)
		}
		purchaseBill.provider = data.provider
		purchaseBill.comments = data.comments
		purchaseBill.merge();
	}
	
	def deleteBills(def ids){
		assert ids : X("需要删除的采购单id不能为空")
		ids.split(",").each{
			deleteBill(Long.parseLong(it))
		}
	}
	
	def deleteBill(long id){
		Operator oper = loginService.currentOperator()
		PurchaseBill pBill = PurchaseBill.load(id)
		assert pBill : X("未找到采购单"+ id)
		logService.log(102011,oper.name+"删除采购单"+ "(" + pBill.id + ")")
		//关联的钻石更新
		List pBillOfDiamonds = Diamond.findByPurchaseBill(pBill)
		pBillOfDiamonds.each(){
			it.purchaseBill=null  //解除关联采购单
			if(pBill.order){
				assert it.order==pBill.order : X("订单采购，采购单关联的钻石与订购单关联的钻石不一致")
			}
			println it.id+" 的 diamondStatus="+it.diamondStatus
			if(pBill.type==1 || pBill.type==3 ){
				it.remove();
			}else{
				it.persistOrMerge()
			}
			
		}
		//解除关联的订单	
		if(pBill.order){
			Order oldOrder=pBill.order;
			oldOrder.orderStatus=2;				//2,已提交
			oldOrder.persistOrMerge()
		}
		pBill.remove()
		return true
	}
	
	def saveDiamond(Diamond diamond) {
		assert diamond: X("钻石为空")
		diamond.persistOrMerge()
	}
	
	def getPurchaseBill(def uniqueCode){
//		def bill=PurchaseBill.load(orderId)
		def bill=PurchaseBill.loadByUniqueCode(uniqueCode)
		def apply=[bill]
		println "bill.id="+bill.id
		println "bill.uniqueCode="+bill.uniqueCode
		apply+=[bill.org.name,bill.oper.name]
		String diamondIds=""
		String orderIds=""
		List pBillOfDiamonds = Diamond.findByPurchaseBill(bill)
		if(pBillOfDiamonds){
			pBillOfDiamonds.each(){
				diamondIds+=it.id+","
				if(bill.type==2){
					orderIds+=it?.order?.id+","
					println "diamond.order.id="+it?.order?.id
				}
				
			}
			diamondIds=diamondIds.substring(0,diamondIds.length()-1)
			if(bill.type==2){
				orderIds=orderIds.substring(0,orderIds.length()-1)
			}
			println "diamondIds="+diamondIds
			println "orderIds="+orderIds
		}
		apply+=[diamondIds]
		apply+=[orderIds]
		def diamond=Diamond.loadByOrder(bill.order)
		println "diamond.id="+diamond.id
		apply+=[diamond]
		return apply
	}
	
	def confirmPurchaseBill(long id,long amount){
		
		Diamond diamonds = ejbService.loadByStmt("from Diamond as o where o.purchaseBill.id=?",id)
		
//		String sql = """
//			select o.id
//			from Diamond as o
//			join o.purchaseBill as p
//			where p.id>=?  
//			order by o.id asc
//		"""
//		Query query = ejbService.createSQLQuery(sql)
//		query.setParameter(0,id)
//		int start = 0
//		int maxResult = 3000
//		query.setFirstResult(start)
//		query.setMaxResults(maxResult)
//		List list = query.list()
		assert diamonds: X("没有为采购单添加钻石")
//		assert amount==list.size() : X("采购的钻石数量与添加的数量不一致")
		if(diamonds){
			def bill=PurchaseBill.load(id)
			bill.purchaseBillStatus=2
			bill.merge();
		}else{
			return false;
		}
		logService.log(102012,"确认采购单")
		return true;
	}
	
	def goNextStep(long id,int nextStatus){
		def bill=PurchaseBill.load(id)
		bill.purchaseBillStatus = nextStatus
		bill.merge();
		def apply=[bill]
		apply+=[bill.org.name,bill.oper.name]
		
		println "nextStatus="+nextStatus
//		采购入库，把关联的钻石的状态改为“在库”状态，导入时更改
//		if(nextStatus==4){
//			List diamonds = Diamond.findByPurchaseBill(bill)
//			println "diamonds.size()="+diamonds.size()
//			diamonds.each(){
//				it.diamondStatus=1  //在库
//				println "it.diamondStatus="+it.diamondStatus
//				it.persistOrMerge()
//			}
//		}
		if(nextStatus==4){
			logService.log(102013,"采购")
		}else if(nextStatus == 5){
			logService.log(102014,"采购后导入")
		}
		
		return apply
	}
	
}